﻿using FTBS.Models.BLO;
using FTBS.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FTBS.Controllers
{
    public class LevelController : Controller
    {
        LevelBLO _levelBLO = new LevelBLO();

        public ActionResult Index()
        {
            return View(_levelBLO.LoadLevels());
        }

        //--------------Create--------------------------
        public ActionResult Create()
        {
            this.Session["LevelName"] = null;
            return View();
        }

        [HttpPost]
        public ActionResult Create(Level level)
        {
            if (ModelState.IsValid)
            {
                if (!_levelBLO.CheckIsExisted(level))
                {
                    this.Session["LevelName"] = null;
                    _levelBLO.CreateLevel(level);
                    return RedirectToAction("Index");
                }
                this.Session["LevelName"] = level.LevelName;
                return View(level);
            }
            return View(level);
        }
        //------------Edit------------------------------
        public ActionResult Edit(int levId = 0)
        {
            Level level = _levelBLO.LoadLevelById(levId);
            if (level == null)
            {
                return HttpNotFound();
            }

            this.Session["curName"] = level.LevelName;
            this.Session["LevelName"] = null;
            return View(level);

        }
        [HttpPost]
        public ActionResult Edit(Level level)
        {
            if (ModelState.IsValid)
            {

                int compare = String.Compare(level.LevelName, (String)this.Session["curName"]);
                if (!_levelBLO.CheckIsExisted(level) || (_levelBLO.CheckIsExisted(level) && compare == 0))
                {
                    this.Session["LevelName"] = null;
                    _levelBLO.EditLevel(level);
                    return RedirectToAction("Index");
                }
                else if (_levelBLO.CheckIsExisted(level) && compare != 0)
                {
                    this.Session["LevelName"] = level.LevelName;
                    return View(level);
                }
            }
            return View(level);
        }
        //------------------Delete---------------------
        [HttpDelete, ActionName("Delete")]
        public ActionResult Delete(int id = 0)
        {
            Level level = _levelBLO.LoadLevelById(id);
            if (level == null)
            {
                return HttpNotFound();
            }
            _levelBLO.DeleteLevel(level);
            return RedirectToAction("Index");
        }
    }
}
